package com.cn.qgx428.orderingmeal.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ProviderInfo;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.qgx428.orderingmeal.R;
import com.cn.qgx428.orderingmeal.adapter.MineCardAdapter;
import com.cn.qgx428.orderingmeal.myClass.BankInfo;
import com.cn.qgx428.orderingmeal.myClass.Bankcard;
import com.cn.qgx428.orderingmeal.myClass.User;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by QinX on 2017/5/7.
 */

public class MineBankCard extends Dialog implements View.OnClickListener {

    private static String TAG = "MineBankCard";

    private Context context;

    private String userID;

    private EditText bankcardInput;
    private TextView bankName;
    private LinearLayout addBankcardBtn;
    private LinearLayout bankcardInputLayout;
    private TextView sureBtn;
    private TextView cancelBtn;
    private ImageView mine_oprateBankcard_img;

    private RecyclerView recyclerView;
    private MineCardAdapter adapter;

    /**
     * 用于判断是否添加银行卡
     */
    private static final int ADD_BANK = 0;
    private static final int NOT_ADD_BANK = 1;
    private int DO_ADD_BANK = NOT_ADD_BANK;


    /**
     * 用于分隔银行卡卡号
     * 解决分隔时与消除分隔时的逻辑问题 —— 添加时每四位数添加一个空格，删除至空格时，消除空格
     * 避免afterTextChanged 与 onTextChanged 调用时在逻辑上造成的矛盾
     */
    private static final int ADD = 0;
    private static final int SUB = 1;
    private int OPRATE =ADD;
    private int cardAmout = 0;

    public MineBankCard(@NonNull Context context, String userID) {
        super(context);

        this.context = context;
        this.userID = userID;
        setMineBackCardView();
    }

    private void setMineBackCardView() {
        View view = LayoutInflater.from(context).inflate(R.layout.mine_mine_bankcard,null);
        bankcardInput = (EditText) view.findViewById(R.id.mine_bankCardInput);
        bankName = (TextView) view.findViewById(R.id.mine_bankName);
        addBankcardBtn = (LinearLayout) view.findViewById(R.id.mine_addBankCard);
        addBankcardBtn.setOnClickListener(this);
        bankcardInputLayout = (LinearLayout) view.findViewById(R.id.mine_bankCardInputLayout);
        mine_oprateBankcard_img = (ImageView) view.findViewById(R.id.mine_oprateBankcard_img);

        sureBtn = (TextView) view.findViewById(R.id.mine_bankCardSure);
        sureBtn.setOnClickListener(this);
        cancelBtn = (TextView) view.findViewById(R.id.mine_bankCardCancel);
        cancelBtn.setOnClickListener(this);

        recyclerView = (RecyclerView) view.findViewById(R.id.mine_cardRecyclyView);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        init();
        setContentView(view);
    }

    private void init() {

        //加载银行卡信息
        getCardData();


        bankcardInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (cardAmout < bankcardInput.getText().length()){
                    OPRATE = ADD;
                } else{
                    OPRATE = SUB;
                }

                //银行卡数字分隔
                if ((bankcardInput.getText().length()+1)%5 == 0 && OPRATE==ADD){
                    StringBuilder CardID = new StringBuilder(bankcardInput.getText().toString());
                    CardID.append(" ");
                    bankcardInput.setText(CardID.toString());
                    //光标移动到行尾部
                    bankcardInput.setSelection(bankcardInput.getText().length());
                }
                //消除银行卡数字分隔
                if ((bankcardInput.getText().length()+1)%5 == 0 && OPRATE==SUB){
                    String str = bankcardInput.getText().toString();
                    str = str.substring(0,str.length()-1);
                    bankcardInput.setText(str);
                    bankcardInput.setSelection(bankcardInput.getText().length());
                }

                cardAmout = bankcardInput.getText().length();
            }

            @Override
            public void afterTextChanged(Editable s) {
                //识别银行名称
                if (bankcardInput.getText().length() ==7){
                    String CardID  = new String(bankcardInput.getText().toString().substring(0,7));
                    CardID = CardID.substring(0,4) + CardID.substring(5,7);
                    int ID = Integer.parseInt(CardID);
                    String name = BankInfo.getBankNameByID(ID);
                    bankName.setText(name);
                    bankName.setVisibility(View.VISIBLE);
                } else if(bankcardInput.getText().length()< 7){
                    bankName.setVisibility(View.GONE);
                }

            }
        });

        bankcardInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                EditText _v=(EditText) v;
                if (!hasFocus) {// 失去焦点
                    _v.setHint(_v.getTag().toString());
                } else {
                    String hint=_v.getHint().toString();
                    _v.setTag(hint);
                    _v.setHint("");
                }
            }
        });
    }

    private void getCardData() {
        //获取银行卡数据，并设置银行卡点击事件
        User user = new User();
        user.setObjectId(userID);
        BmobQuery<Bankcard> query = new BmobQuery<Bankcard>();
        query.addWhereEqualTo("user", new BmobPointer(user));
        query.findObjects(new FindListener<Bankcard>() {
            @Override
            public void done(List<Bankcard> list, BmobException e) {
                if (e == null){
                    if (list.size()>0){
                        setAdapter(list);
                    } else{
                        Log.d(TAG, "获取银行卡数据没有");
                    }
                } else {
                    Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "获取银行卡数据失败 ："+e.getErrorCode()+e.getMessage());
                }
            }
        });
    }

    public void setAdapter(final List<Bankcard> list) {
        //适配器为空配置适配器
        if (adapter == null){
            adapter = new MineCardAdapter(context,list,R.layout.mine_card_item);
            adapter.setOnClickItmeListener(new MineCardAdapter.OnItemClickListener() {
                @Override
                public void onItemLongClick(View view, int position, String CardID) {
                    showNormalDialog(list.get(position).getObjectId());
                }
            });
            recyclerView.setAdapter(adapter);
        }
        //已有适配器更新适配器数据
        else {
            adapter.appendList(list);
            adapter.setOnClickItmeListener(new MineCardAdapter.OnItemClickListener() {
                @Override
                public void onItemLongClick(View view, int position, String CardID) {
                    showNormalDialog(list.get(position).getObjectId());
                    Toast.makeText(context, CardID, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }


    /**
     *删除银行卡确认对话框
     */
    private void showNormalDialog(final String CardID) {
        AlertDialog.Builder alerDialog = new AlertDialog.Builder(context);
        alerDialog.setMessage("删除银行卡？");
        alerDialog.setPositiveButton("删除", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Bankcard bankCard = new Bankcard();
                final User user = new User();
                user.setObjectId(userID);
                bankCard.setUser(user);
                bankCard.setObjectId(CardID);
                bankCard.delete(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null){
                            BmobQuery<Bankcard> query = new BmobQuery<Bankcard>();
                            query.addWhereEqualTo("user",new BmobPointer(user));
                            query.findObjects(new FindListener<Bankcard>() {
                                @Override
                                public void done(List<Bankcard> list, BmobException e) {
                                    if (e == null){
                                        setAdapter(list);
                                        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                                    } else{
                                        Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                                        Log.d(TAG, "删除银行卡后更新页面数据："+e.getMessage()+e.getErrorCode());
                                    }
                                }
                            });
                        }else {
                            Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show();
                            Log.d(TAG, "删除银行卡 ："+e.getErrorCode()+e.getMessage());
                        }
                    }
                });
            }
        });
        alerDialog.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
            }
        });
        alerDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mine_addBankCard:
                changeBankLayout(DO_ADD_BANK);
                break;
            case R.id.mine_bankCardSure:
                Toast.makeText(context, bankcardInput.getText().toString(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.mine_bankCardCancel:
                dismiss();
        }
    }

    private void changeBankLayout(int do_add_bank) {
        if (do_add_bank == NOT_ADD_BANK){
            bankcardInputLayout.setVisibility(View.VISIBLE);
            mine_oprateBankcard_img.setImageResource(R.drawable.substact_corner_black);
            DO_ADD_BANK = ADD_BANK;
        } else if (do_add_bank == ADD_BANK){
            bankcardInputLayout.setVisibility(View.GONE);
            mine_oprateBankcard_img.setImageResource(R.drawable.add_character);
            DO_ADD_BANK = NOT_ADD_BANK;
        }
    }

    public String getCardID(){
        return bankcardInput.getText().toString();
    }

    public Boolean isADDBankcard(){
        return DO_ADD_BANK == ADD_BANK ? true : false;
    }

    public String getCardCat(){
        return bankName.getText().toString();
    }

    public void setSubmitBtn(View.OnClickListener listener){
        sureBtn.setOnClickListener(listener);
    }

    public void changeBankcartLayoutAfterOperate(){
        changeBankLayout(ADD_BANK);
        bankName.setText("");
        bankcardInput.setText("");
    }
}
